package com.zhuhjay.boot.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zhuhjay.constant.MessageConstant;
import com.zhuhjay.constant.RedisMessageConstant;
import com.zhuhjay.domain.entity.Order;
import com.zhuhjay.domain.http.Result;
import com.zhuhjay.service.OrderService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhuhjay
 * @since 2022-04-02
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    private final StringRedisTemplate redisTemplate;
    public OrderController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Reference
    private OrderService orderService;

    @PostMapping
    public Result add(@RequestBody Map<String, Object> formData){
        try{
            // 验证 验证码
            String code = redisTemplate.opsForValue()
                    .get(RedisMessageConstant.SENDTYPE_ORDER + ":" + formData.get("telephone"));
            String validateCode = (String) formData.get("validateCode");
            if( code != null && code.equals(validateCode) ){
                // 设置预约类型
                formData.put("orderType", Order.ORDERTYPE_WEIXIN);
                Result result = orderService.add(formData);
                if( result.isFlag() ){
                    // 发短信提醒用户预约成功
                    System.out.println("发送短信给用户, 提醒用户体检");
                }
                return result;
            }else{
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
        }catch (Exception e){
            return new Result(false, MessageConstant.ORDER_FULL);
        }
    }

    @GetMapping("/{id}")
    public Result finById(@PathVariable("id") Integer id){
        try{
            Map<String, Object> map = orderService.findInfoById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        }catch (Exception e){
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

}
